const express = require('express');
const db = require('../db');
//引入中间件
const multer = require('multer');
var fs = require('fs');
  const path = require('path'); // 导入 path 模块
const moment = require('moment');
const { reverse } = require('dns');
//使用multer解析FormData数据
const storage = multer.memoryStorage(); // 将文件存储在内存中
const upload = multer({ storage: storage });
const USER_STATUS = ['ONLINE', 'OFFLINE'];
const users = {};

function socket(io){
    // 假设这里有一个储存在预约与 Socket 的对象:
    const appointmentSockets = {};
    io.on('connection', (socket) => {
       console.log('socket连接成功！');
       //进入聊天页加入房间号
       socket.on('join', (data) => {
        // 根据角色来区分咨询师和用户
       if (data.role === "counselor") {
         // 咨询师
         users["counselor_" +data.senderId] = socket.id
       } else if (data.role === "normal") {
         // 用户
         console.log(data.role)
         users["user_" + data.senderId] = socket.id;
       }
        // console.log(users)
      });
        //监听login事件
        socket.on('login', (speaker) => {
            console.log(speaker.name, "已登录")
            //通知所有客户端（除了自己）更新在线聊天成员
            socket.broadcast.emit('updateSpeaker', speaker);
        })

        //一对一接收发送者发送过来的消息
        socket.on('chatMessage', async(data) => {
            const {senderId,receiverId,content,sendTime,role}=data
            //设置发消息的类型，0为文字，1为图片，2为视频
            const content_type=0
             // 保存消息到数据库
             try {
              let sender_type=role==="normal"?"user":"counselor";
              let receiver_type=role==="normal"?"counselor":"user";
              const insertQuery='INSERT INTO messages (sender_id,receiver_id,sender_type,receiver_type,content,content_type,send_time) VALUES(?,?,?,?,?,?,?) '
              db.query(insertQuery,[senderId,receiverId,sender_type,receiver_type,content,content_type,sendTime],(err,rows)=>{
                if (err) {
                  console.error('数据库插入错误:', err);
                  return;
                }
                let receiver = role === "normal" ? "counselor_" + receiverId : "user_" + receiverId;
                const toSocketId = users[receiver];
                if (toSocketId) {
                  
                    io.to(toSocketId).emit('receiveChatMsg', data); // 发送消息给接收方
                }
                })
              } catch (error) {
                 console.error('数据库存储出错:', error);
              }
        });
        
        //socket异常捕获消息
        socket.on('error', (event) => {
          // 错误异常消息
          console.log('error')
        })

        socket.on('disconnect', () => {
          console.log('socket连接已断开！');
            // 清理断开连接的用户信息
            const disconnectedSocketId = socket.id;
            // 遍历用户信息对象，查找并移除断开连接的用户信息
            for (const key in users) {
                if (users[key] === disconnectedSocketId) {
                    delete users[key]; // 从用户信息对象中删除断开连接的用户信息
                    console.log(`User with socket id ${disconnectedSocketId} has disconnected.`);
                    break; // 找到一个匹配后退出循环
                }
    }

        });
      });
  
}

module.exports=socket